import { message } from "antd";
import React, { useEffect } from "react";
import { useLocation, useHistory } from "react-router-dom";
import { _authByWeixin, _loginByWeixin } from './service';
// import { globalContext, setSteteContext } from "@/service/globalState";

const LoginRes: React.FC = () => {
    const location = useLocation();
    const history = useHistory();
    const openId = localStorage.getItem('openId')
    const wx_token = localStorage.getItem('wx_token')

    useEffect(() => {
        const fetchData = async () => {

            const code = location.search.substring(1)?.split('&')[0]?.split('=')[1];
            if (openId === null || wx_token === null) {
                !!code ? await _authByWeixin({ code: code }).then((dataRes) => {
                    localStorage.setItem("openId", dataRes.data.data.openid);
                    localStorage.setItem("wx_token", dataRes.data.data.token);
                    history.push('/bindPhone')
                })
                    : message.error('请先授权微信登录', 5)
            } else {
                await _loginByWeixin({
                    wx_token: wx_token,
                    openid: openId
                }).then(async(dataRes) => {
                    if (dataRes.data.code === 200) {
                        localStorage.setItem("token", dataRes.data.token);
                        localStorage.setItem("role", dataRes.data.data.role);
                        dataRes.data.code === 200 && history.push('/')

                    }else{
                        !!code ? await _authByWeixin({ code: code }).then((dataRes) => {
                            localStorage.setItem("openId", dataRes.data.data.openid);
                            localStorage.setItem("wx_token", dataRes.data.data.token);
                            history.push('/bindPhone')
                        })
                            : message.error('请先授权微信登录', 5)
                    }
                })
            }


        }
        fetchData();
    }, [])

    return (
        <>
        </>
    )
}

export default LoginRes;
